package com.shanzmoo.db.third.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.base.constant.Constant;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.MallOrderStatus;
import com.shanzmoo.base.exception.OutletBusinessException;
import com.shanzmoo.db.report.entity.vo.ProductSalesVO;
import com.shanzmoo.db.third.entity.PlatformOrderEntity;
import com.shanzmoo.db.third.entity.ThirdProductSkuEntity;
import com.shanzmoo.db.third.entity.bo.PlatformOrderAddLogisticsBO;
import com.shanzmoo.db.third.entity.bo.PlatformOrderExcelBO;
import com.shanzmoo.db.third.entity.bo.PlatformOrderSellerRemarkBO;
import com.shanzmoo.db.third.entity.query.PlatformlOrderPageQuery;
import com.shanzmoo.db.third.entity.vo.PlatformOrderPageVO;
import com.shanzmoo.db.third.mapper.PlatformOrderMapper;
import com.shanzmoo.db.third.service.IPlatformOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanzmoo.db.third.service.IThirdProductSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 第三方平台订单 服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2021-01-07
 */
@Service
public class PlatformOrderServiceImpl extends ServiceImpl<PlatformOrderMapper, PlatformOrderEntity> implements IPlatformOrderService {

    @Autowired
    private IThirdProductSkuService thirdProductSkuService;

    @Override
    public SResponse<PageRespBase<PlatformOrderPageVO>> getPageList(PlatformlOrderPageQuery query) {
        Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());

        List<PlatformOrderEntity> list = baseMapper.selectList(
                new QueryWrapper<PlatformOrderEntity>()
                        .eq("deleted", false)
                        .eq(query.getStatus() != null, "status", query.getStatus())
                        .like(StrUtil.isNotBlank(query.getOrderNo()), "order_no", query.getOrderNo())
                        .like(StrUtil.isNotBlank(query.getPurchaser()), "purchaser", query.getPurchaser())
                        .orderByDesc("order_time")
        );
        if (CollectionUtil.isEmpty(list)) {
            return SResponse.ok(PageRespBase.empty(query.getPageSize()));
        }

        List<PlatformOrderPageVO> reList = list.stream().map(PlatformOrderPageVO::create).collect(Collectors.toList());

        PageRespBase<PlatformOrderPageVO> re = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return SResponse.ok(re);
    }

    @Override
    public SResponse<Boolean> addLogistics(PlatformOrderAddLogisticsBO logistics, Integer currentUserId) {
        PlatformOrderEntity orderEntity = baseMapper.selectOne(
                new QueryWrapper<PlatformOrderEntity>()
                        .eq("id", logistics.getId())
                        .eq("status", MallOrderStatus.WAIT_SEND)
        );
        if (orderEntity == null){
            return SResponse.fail(Constant.ERRCODE_LOGIC, "请选择待发货订单");
        }

        orderEntity.setLogisticsNo(logistics.getLogisticsNo());
        orderEntity.setLogisticsType(logistics.getLogisticsType());
        orderEntity.setDeliveryTime(LocalDateTime.now());
        orderEntity.setStatus(MallOrderStatus.ALREADY_SEND);
        orderEntity.setUpdateUser(currentUserId);
        baseMapper.updateById(orderEntity);

        return SResponse.ok(Boolean.TRUE);
    }

    @Override
    public SResponse<Boolean> addSellerRemark(PlatformOrderSellerRemarkBO sellerRemark, Integer currentUserId) {
        PlatformOrderEntity orderEntity = baseMapper.selectOne(
                new QueryWrapper<PlatformOrderEntity>()
                        .eq("id", sellerRemark.getId())
        );
        if (orderEntity == null){
            return SResponse.fail(Constant.ERRCODE_LOGIC, "请输入正确订单id");
        }
        orderEntity.setSellerRemark(sellerRemark.getSellerRemark().trim());
        orderEntity.setUpdateUser(currentUserId);
        baseMapper.updateById(orderEntity);

        return SResponse.ok(Boolean.TRUE);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SResponse<Boolean> importByExcel(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<PlatformOrderExcelBO> excelDataList = reader.readAll(PlatformOrderExcelBO.class);

            List<PlatformOrderEntity> orderEntityList = JSON.parseArray(JSON.toJSONString(excelDataList), PlatformOrderEntity.class);
            //先查出所有的信息
            List<ThirdProductSkuEntity> thirdProductSkuList = thirdProductSkuService.list(new QueryWrapper<ThirdProductSkuEntity>().eq("deleted", false));
            orderEntityList.forEach(e->{
                if (StrUtil.isBlank(e.getPlatformCode())){
                    throw new OutletBusinessException("订单：" + e.getOrderNo() + "，缺少商品code信息");
                }
                if (e.getSkuNum() == null){
                    throw new OutletBusinessException("订单：" + e.getOrderNo() + "，缺少商品数量信息");
                }
                Boolean mark = Boolean.TRUE;
                //根据类型和第三方sku匹配系统sku编码
                for (ThirdProductSkuEntity ee : thirdProductSkuList) {
                    if (ee.getPlatform() == e.getPlatform() && StrUtil.isNotBlank(ee.getThirdSku())
                            && ee.getThirdSku().equals(e.getPlatformCode())) {
                        e.setSku(ee.getSku());
                        mark = Boolean.FALSE;
                        break;
                    }
                }
                if(mark)throw new OutletBusinessException("第三方平台编码：" + e.getPlatform() + "，第三方平台sku编码:"+e.getPlatformCode()+".匹配系统sku编码失败");
            });
            this.saveBatch(orderEntityList);

            return SResponse.ok(Boolean.TRUE);
        } catch (IOException e) {
            log.error("上传文件获取失败", e);
            return SResponse.fail(Constant.ERRCODE_LOGIC, "Excel文件获取失败");
        }
    }

    @Override
    public List<ProductSalesVO> getProductSales() {
        return baseMapper.getProductSales();
    }
}
